package com.my.study.utils;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import javax.xml.bind.DatatypeConverter;
import java.util.Objects;

/**
 * @author luyuhao
 * @since 2020/8/25 21:05
 */
public class DESEncryptForYptUtil {

    public static String encrypt(String xml, String key) throws Exception {
        return toSpecialBase64(encrypt(xml.getBytes("UTF-16LE"), key));
    }

    private static String toSpecialBase64(byte[] data) {
        String result = "";
        if(Objects.nonNull(data)){
            result = DatatypeConverter.printBase64Binary(data);
            result = result.replaceAll("\\+", "!");
            result = result.replaceAll("/", "-");
            result = result.replaceAll("=", "_");
        }
        return result;
    }

    public static byte[] encrypt(byte[] arrB, String key) throws Exception {
        DESKeySpec desKeySpec = new DESKeySpec(key.getBytes());
        byte[] ivkey = key.getBytes();
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
        IvParameterSpec ivp = new IvParameterSpec(ivkey);

        Cipher encryptCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        encryptCipher.init(Cipher.ENCRYPT_MODE, secretKey, ivp);
        return encryptCipher.doFinal(arrB);
    }
}
